import axios from "axios"
import config from "@/config"
import nprogress from "nprogress"
import store from "@/store"
import router from "@/router"

const request = axios.create({
    baseURL:config.baseURL,
    timeout:config.timeout,
    withCredentials:true
})

request.interceptors.request.use((config)=>{
     nprogress.start();
     config.headers["token"] = store.state.user.token;
     return config;
})

request.interceptors.response.use((res)=>{
     console.log("Response: ",res.data);
     if(res.data.code === 403){
         return alert(res.data.message)
     }
     if(res.data.code < 2){
          res.isExpireToken = true;
          router.msg = res.data.message; 
          store.dispatch("user/setExpire",0)
          router.replace({
               path:"/login"
          }).catch(err=>{});
     }else if(res.data.code === 2){
          store.dispatch("user/setExpire",res.data.data.expire)
     }
     nprogress.done();
     return res;
})


export default request;